package com.wang.chatai.controller;

import com.wang.chatai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RestController
@RequiredArgsConstructor
@RequestMapping("/ai")
public class CustomerServiceController {

    public final ChatClient serviceChatClient;

    private final ChatHistoryRepository chatHistoryRepository;

    /**
     * 智能客服
     * 目前SpringAI的OpenAI客户端与阿里云百炼存在兼容性问题，所以FunctionCalling功能无法使用stream模式。
     * 可以使用call来调用，也可以自定义AlibabaOpenAiChatModel。
     */
    @RequestMapping(value = "/service")
    public Flux<String> chat(String prompt, String chatId) {
        //保存会话id
        chatHistoryRepository.save("service", chatId);
        //请求模型
        return serviceChatClient
                .prompt()
                .user(prompt)
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)) //接收前端穿的消息id，存到上下文里面
                .stream()
                .content();
    }

}
